package com.sdy.dcsb.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.sdy.common.model.Response;
import com.sdy.dcsb.biz.model.*;
import com.sdy.dcsb.biz.service.*;
import com.sdy.dcsb.biz.service.EsbSystemService;
import com.sdy.mvc.controller.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.List;
import static org.springframework.util.StringUtils.isEmpty;

@Slf4j
@RestController
@RequestMapping("/esbAtomServiceDetailed")
@Api(tags = "原子服务相关接口")
public class EsbAtomServiceController extends BaseController {
    @Autowired
    private EsbAtomServiceService esbAtomServiceDetailedService;
    @Autowired
    private EsbSystemService esbSystemService;
    @Autowired
    private EsbInboundMainService esbInboundMainService;
    @Autowired
    private UserOperationLogService userOperationLogService;
    @Autowired
    private EsbAdapderHttpService esbAdapderHttpService;
    @Autowired
    private EsbAdapderSoapService esbAdapderSoapService;

    @GetMapping("/selectServiceList")
    @ApiOperation("查询原子服务清单，分页，可按编码或名称模糊查询和服务状态查询")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "type", value = "查询类别,1:服务名称 2:服务编码 其他:查全部"),
            @ApiImplicitParam(dataType = "String", name = "message", value = "查询值"),
            @ApiImplicitParam(dataType = "String", name = "status", value = "查询状态,全部:2 在用:1 不在用:0"),
            @ApiImplicitParam(dataType = "Integer", name = "current", value = "当前页"),
            @ApiImplicitParam(dataType = "Integer", name = "size", value = "每页数量"),
    })
    public Response selectServiceList(String type, String message, String status, Integer current, Integer size) {
        try {
            if(!isEmpty(message)) {
                message = URLDecoder.decode(message,"utf-8");
            }
        }catch(IOException e) {

        }
        if("2".equals(status)) {
            status = "0,1";
        }
        JSONObject object = new JSONObject();
        if(isEmpty(current)) {
            current = 1;
        }
        if(isEmpty(size)) {
            size = 10;
        }
        object.put("size",size);
        object.put("current",current);
        object.put("searchCount",true);

        Integer total = 0;
        Integer page = 0;

        if(!isEmpty(message)) {
            if(type.equals("1")) {
                List<EsbAtomserviceVo> resultCount = esbAtomServiceDetailedService.findAtomServiceListCount("atomservice_name", message, status);
                total = resultCount.size();
                if(total%size==0){
                    page = total/size;
                }else {
                    page = total/size+1;
                }
                List<EsbAtomserviceVo> result = esbAtomServiceDetailedService.findAtomServiceList("atomservice_name", message, status, current, size);
                object.put("records",result);
                object.put("total",total);
                object.put("pages",page);
            }else if(type.equals("2")) {
                List<EsbAtomserviceVo> resultCount = esbAtomServiceDetailedService.findAtomServiceListCount("atomservice_code", message, status);
                total = resultCount.size();
                if(total%size==0){
                    page = total/size;
                }else {
                    page = total/size+1;
                }
                List<EsbAtomserviceVo> result = esbAtomServiceDetailedService.findAtomServiceList("atomservice_code", message, status, current, size);
                object.put("records",result);
                object.put("total",total);
                object.put("pages",page);
            }else {
                return Response.error("请输入指定的查询类别");
            }
        }else {
            List<EsbAtomserviceVo> resultCount = esbAtomServiceDetailedService.findAtomServiceListCount("atomservice_name",message,status);
            total = resultCount.size();
            if(total%size==0){
                page = total/size;
            }else {
                page = total/size+1;
            }
            List<EsbAtomserviceVo> result = esbAtomServiceDetailedService.findAtomServiceList("atomservice_name",message, status,current, size);
            object.put("records",result);
            object.put("total",total);
            object.put("pages",page);
            return Response.success(object);
        }
        return Response.success(object);
    }

    @GetMapping("/detailMess")
    @ApiOperation("详情")
    public Response detailMess(Integer id) {
        if(!isEmpty(id)) {
            return Response.success(esbAtomServiceDetailedService.selectById(id));
        }else {
            return Response.error("请求id不能为空");
        }
    }

    @GetMapping("/detailRepertoireMess")
    @ApiOperation("原子服务清单详情接口")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "原子服务id"),
    })
    public Response detailRepertoireMess(Integer id) {
        if(!isEmpty(id)) {
            return Response.success(esbAtomServiceDetailedService.selectAllMess(id));
        }else {
            return Response.error("请求id不能为空");
        }
    }

    @GetMapping("/detailSystemMess")
    @ApiOperation("系统信息详情")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "系统id"),
    })
    public Response detailSystemMess(Integer id) {
        if(!isEmpty(id)) {
            return Response.success(esbSystemService.getById(id));
        }else {
            return Response.error("请求id不能为空");
        }
    }

    /**
     * 原子服务
     */
    @GetMapping("/selectAtomService")
    @ApiOperation("原子服务，分页，可按编码或名称模糊查询,id必传")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "当前节点id"),
            @ApiImplicitParam(dataType = "Integer", name = "current", value = "当前页"),
            @ApiImplicitParam(dataType = "Integer", name = "size", value = "每页数量"),
            @ApiImplicitParam(dataType = "Integer", name = "type", value = "查询类别,1:接口名称 2:接口编码 其他:查全部"),
            @ApiImplicitParam(dataType = "String", name = "message", value = "查询值"),
    })
    public Response selectAtomService(Integer id, Integer current, Integer size, Integer type, String message) {
        JSONObject object = new JSONObject();
        if(isEmpty(current)) {
            current = 1;
        }
        if(isEmpty(size)) {
            size = 10;
        }
        object.put("size",size);
        object.put("current",current);
        object.put("searchCount",true);

        Integer total = 0;
        Integer page = 0;

        if(!isEmpty(message)) {
            try {
                message = URLDecoder.decode(message,"utf-8");
            }catch(IOException e) {

            }
            if(type.equals(1)) {
                List<EsbAtomservice> resultCount = esbAtomServiceDetailedService.findCountAtomServiceByIdType(id,"atomservice_name", message);
                total = resultCount.size();
                if(total%size==0){
                    page = total/size;
                }else {
                    page = total/size+1;
                }
                List<EsbAtomservice> result = esbAtomServiceDetailedService.findAllAtomServiceByIdType(id, current, size, "atomservice_name",message);
                object.put("records",result);
                object.put("total",total);
                object.put("pages",page);
            }else if(type.equals(2)) {
                List<EsbAtomservice> resultCount = esbAtomServiceDetailedService.findCountAtomServiceByIdType(id,"atomservice_code", message);
                total = resultCount.size();
                if(total%size==0){
                    page = total/size;
                }else {
                    page = total/size+1;
                }
                List<EsbAtomservice> result = esbAtomServiceDetailedService.findAllAtomServiceByIdType(id, current, size,"atomservice_code", message);
                object.put("records",result);
                object.put("total",total);
                object.put("pages",page);
            }else {
                List<EsbAtomserviceVo> resultCount = esbAtomServiceDetailedService.findCountAtomServiceById(id);
                total = resultCount.size();
                if(total%size==0){
                    page = total/size;
                }else {
                    page = total/size+1;
                }
                List<EsbAtomserviceVo> result = esbAtomServiceDetailedService.findAllAtomServiceById(id, current, size);
                object.put("records",result);
                object.put("total",total);
                object.put("pages",page);
                return Response.success(object);
            }
        }else {
            List<EsbAtomserviceVo> resultCount = esbAtomServiceDetailedService.findCountAtomServiceById(id);
            total = resultCount.size();
            if(total%size==0){
                page = total/size;
            }else {
                page = total/size+1;
            }
            List<EsbAtomserviceVo> result = esbAtomServiceDetailedService.findAllAtomServiceById(id, current, size);
            object.put("records",result);
            object.put("total",total);
            object.put("pages",page);
        }
        return Response.success(object);
    }

    @GetMapping("/saveOrUpdateAtomService")
    @ApiOperation("新增或修改单条原子服务信息")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "当前服务id"),
            @ApiImplicitParam(dataType = "String", name = "atomserviceName", value = "原子服务名称"),
            @ApiImplicitParam(dataType = "String", name = "atomserviceVersion", value = "服务版本"),
            @ApiImplicitParam(dataType = "String", name = "status", value = "工作状态,1:工作态,0:注销态"),
            @ApiImplicitParam(dataType = "String", name = "overTime", value = "超时时间/ms（最小30000）"),
            @ApiImplicitParam(dataType = "String", name = "maxClients", value = "最大连接数"),
            @ApiImplicitParam(dataType = "String", name = "adapterType", value = "适配类型"),
            @ApiImplicitParam(dataType = "String", name = "contentType", value = "请求头类型"),
            @ApiImplicitParam(dataType = "String", name = "atomserviceCode", value = "原子服务编码")
    })
    public Response save(HttpServletRequest request, Integer id, String atomserviceName, String adapterType, String contentType,
                         String maxClients, String atomserviceVersion, String status, String overTime, String atomserviceCode, Integer systemId) {
        try {
            atomserviceName = URLDecoder.decode(atomserviceName,"utf-8");
        }catch(IOException e) {

        }
        EsbAtomservice esbAtomservice = new EsbAtomservice();
        esbAtomservice.setAtomserviceName(atomserviceName);
        esbAtomservice.setAdapterType(adapterType);
        esbAtomservice.setAtomserviceVersion(atomserviceVersion);
        esbAtomservice.setMaxClients(maxClients);
        esbAtomservice.setStatus(status);
        esbAtomservice.setContentType(contentType);
        esbAtomservice.setOverTime(overTime);
        esbAtomservice.setAtomserviceCode(atomserviceCode);
        esbAtomservice.setSystemId(systemId);

        if (isEmpty(id)){
            List<EsbAtomservice> esbAtomserviceResult = esbAtomServiceDetailedService.selectAtomServiceByCode(atomserviceCode);
            if(esbAtomserviceResult.size() >= 1) {
                return Response.error("原子服务编码已存在，请重新输入");
            }
            esbAtomservice.setCreateTime(new Date());
            if (isEmpty(overTime)){
                esbAtomservice.setOverTime("30000");
            }
            if (isEmpty(maxClients)) {
                esbAtomservice.setMaxClients("1000");
            }
            if (isEmpty(atomserviceVersion)){
                esbAtomservice.setAtomserviceVersion("1");
            }
            userOperationLogService.savaUserLog(request, "新增原子服务：" + atomserviceCode);
            return Response.success(esbAtomServiceDetailedService.save(esbAtomservice));
        }else {
            esbAtomservice.setUpdateTime(new Date());
            EsbAtomservice atomOne = esbAtomServiceDetailedService.selectById(id);
            if (atomOne.getAtomserviceName().equals(atomserviceName) && atomOne.getAtomserviceCode().equals(atomserviceCode) && atomOne.getStatus().equals(status) && atomOne.getMaxClients().equals(maxClients) && atomOne.getContentType().equals(contentType) && atomOne.getAdapterType().equals(adapterType) && atomOne.getOverTime().equals(overTime) && atomOne.getSystemId().equals(systemId) && atomOne.getAtomserviceVersion().equals(atomserviceVersion)){
                return Response.error("信息无变化");
            }else {
                userOperationLogService.savaUserLog(request, "修改原子服务：" + atomserviceCode);
                boolean update = esbAtomServiceDetailedService.update(esbAtomservice,new UpdateWrapper<EsbAtomservice>().eq("id",id));
                return Response.success(update);
            }
        }
    }

    @GetMapping("/deleteAtomServiceById")
    @ApiOperation("删除单条原子服务数据")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "原子服务id"),
    })
    public Response deleteAtomServiceById(HttpServletRequest request, Integer id) {
        if(isEmpty(id)) {
            return Response.error("请求id不能为空");
        }
        String atomServiceCode = esbAtomServiceDetailedService.selectById(id).getAtomserviceCode();
        QueryWrapper<EsbInboundMain> wrapper = new QueryWrapper<>();
        wrapper.eq("atomcode", atomServiceCode);

        if (esbInboundMainService.list(wrapper).size() != 0) {
            return Response.error("删除出错，存在已关联的服务!");
        }
        userOperationLogService.savaUserLog(request, "删除原子服务：" + atomServiceCode);
        boolean remove = esbAtomServiceDetailedService.removeById(id);
        if (remove){
            EsbAdapderHttp esbAdapderHttp = esbAdapderHttpService.getById(id);
            EsbAdapderSoap esbAdapderSoap = esbAdapderSoapService.getById(id);
            if (!isEmpty(esbAdapderHttp)){
                esbAdapderHttpService.removeById(id);
            }
            if (!isEmpty(esbAdapderSoap)){
                esbAdapderSoapService.removeById(id);
            }
        }
        return Response.success("删除成功!");
    }

}